package org.example.domain.activity.service.trial.node;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.activity.model.entity.MarketProductEntity;
import org.example.domain.activity.model.entity.TrialBalanceEntity;
import org.example.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import org.example.domain.activity.model.valobj.SkuVO;
import org.example.domain.activity.service.discount.IDiscountCalculateService;
import org.example.domain.activity.service.trial.AbstractGroupBuyMarketSupport;
import org.example.domain.activity.service.trial.factory.DefaultActivityStrategyFactory;
import org.example.domain.activity.service.trial.thread.QueryGroupBuyActivityDiscountVOThreadTask;
import org.example.domain.activity.service.trial.thread.QuerySkuVofromDBThreadTask;
import org.example.types.design.framework.tree.StrategyHandle;
import org.example.types.enums.ResponseCode;
import org.example.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.*;

@Slf4j
@Service
public class MarketNode  extends AbstractGroupBuyMarketSupport<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
private EndNode endNode;

    @Resource
    private ErrorNode errorNode;
    @Resource
    private TagNode tagNode;

    @Resource
    private Map<String, IDiscountCalculateService> discountCalculateServiceMap;

    @Override
    protected void mutiThread(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws ExecutionException, InterruptedException, TimeoutException {
      QueryGroupBuyActivityDiscountVOThreadTask queryGroupBuyActivityDiscountVOThreadTask=new QueryGroupBuyActivityDiscountVOThreadTask(requestParameter.getSource(), requestParameter.getChannel(),requestParameter.getGoodsId(),repository);

        FutureTask<GroupBuyActivityDiscountVO> groupBuyActivityDiscountVOFutureTask = new FutureTask<>(queryGroupBuyActivityDiscountVOThreadTask);
        threadPoolExecutor.execute(groupBuyActivityDiscountVOFutureTask);
        QuerySkuVofromDBThreadTask querySkuVofromDBThreadTask = new QuerySkuVofromDBThreadTask(requestParameter.getGoodsId(), repository);
        FutureTask<SkuVO> skuVOFutureTask=new FutureTask<>(querySkuVofromDBThreadTask);
        threadPoolExecutor.execute(skuVOFutureTask);
        dynamicContext.setGroupBuyActivityDiscountVO(groupBuyActivityDiscountVOFutureTask.get(timeout, TimeUnit.MINUTES));
        dynamicContext.setSkuVO(skuVOFutureTask.get(timeout,TimeUnit.MINUTES));


    }

    @Override
    public TrialBalanceEntity doApply(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        log.info("拼团商品查询试算服务-MarketNode userId:{} requestParameter:{}",requestParameter.getUserId(), JSON.toJSONString(requestParameter));
// todo xfg 拼团优惠试算

        GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = dynamicContext.getGroupBuyActivityDiscountVO();
        if(
                null==groupBuyActivityDiscountVO
        )
        {
            return router(requestParameter,dynamicContext);
        }
        GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount = groupBuyActivityDiscountVO.getGroupBuyDiscount();

        SkuVO skuVO=dynamicContext.getSkuVO();

        if(null==groupBuyDiscount||null==skuVO)
        {
            return  router(requestParameter,dynamicContext);
        }

        IDiscountCalculateService discountCalculateService = discountCalculateServiceMap.get(groupBuyDiscount.getMarketPlan());
        if(null==discountCalculateService)
        {
            log.info("不存在{}类型的折扣计算服务,支持类型为{}",groupBuyDiscount.getMarketPlan(),JSON.toJSONString(discountCalculateService));
            throw new AppException(ResponseCode.E0001.getCode(),ResponseCode.E0001.getInfo());
        }
        BigDecimal payPrice = discountCalculateService.calculate(requestParameter.getUserId(), skuVO.getOriginalPrice(), groupBuyDiscount);
        dynamicContext.setPayPrice(payPrice);
        dynamicContext.setDeductionPrice(skuVO.getOriginalPrice().subtract(payPrice));


        return router(requestParameter,dynamicContext);
    }

    @Override
    public StrategyHandle<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> get(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) {
        if(null==dynamicContext.getGroupBuyActivityDiscountVO()|| null==dynamicContext.getDeductionPrice()|| null==dynamicContext.getSkuVO())
        {
            return errorNode;
        }

        return tagNode;
    }
}
